/**
 * Project: TacticaPescaditos
 * File: MessageDispatcher.java
 */
package org.javahispano.javacup.tacticas_aceptadas.Pescaditos.com.chidotronics.javacup.messages;

import java.util.LinkedList;
import java.util.List;

import org.javahispano.javacup.tacticas_aceptadas.Pescaditos.com.chidotronics.javacup.Player;
import org.javahispano.javacup.tacticas_aceptadas.Pescaditos.com.chidotronics.javacup.TacticaPescaditos;

/**
 * @author Carlos Alberto
 * class: MessageDispatcher
 */
public class MessageDispatcher {



	private LinkedList<Telegram> telegrams;

	private TacticaPescaditos owner;
	
	/**
	 * 
	 */
	public MessageDispatcher(TacticaPescaditos owner) {

		this.owner = owner;
		telegrams = new LinkedList<Telegram>();

	}


	
	public void dispatch( int sender, int receiver, Telegram.MessageType msg, Object extraInfo, int delay){
		
		Telegram telegram = new Telegram(msg,sender,receiver, extraInfo);
		
		if (delay <= 0) {
			owner.getPlayers().get(receiver).handleMessage(telegram);
		} else {
			telegram.setDelay(delay);
			telegrams.addLast(telegram);
		}
		
		
		
	}
	
	public void dispatchDelayed(){
		List<Player<?>> players = owner.getPlayers();
		for (int i = 0; i < telegrams.size(); i++){
			Telegram telegram = telegrams.get(i);
			if (telegram.getDelay()<= 0 ) {
				Player<?> receiver = players.get(telegram.getReceiver());
				
				receiver.handleMessage(telegram);
				telegrams.remove(i);
			}
		}
		
	
	}


}
